<template>
  <div class="shopcar-contain">
    <template v-if="goodsList?.length > 0">
      <div class="bigbox">
        <!-- 收货地址 -->
        <van-contact-card v-if="!$store.state.address.id" type="add" add-text="添加收货地址" @click="onAdd" />
        <div v-else>
          <div class="address" @click="onAdd">
            <div class="left">
              <van-icon name="logistics" />
              <div class="text">
                <div>
                  {{ newAddress.province }}{{ newAddress.city }}{{ newAddress.country }}

                  <van-tag type="danger" v-if="newAddress.isDefault">默认</van-tag>
                </div>
                <span class="particulars">{{ newAddress.addressDetail }}</span>
                <span>{{ newAddress.name }} {{ newAddress.tel }}</span>
              </div>
            </div>
            <van-icon name="arrow" />
          </div>
          <div class="line">
            <div v-for="i in 20" :key="i" :class="['item', 'bg' + (i % 2) + 1]"></div>
          </div>
        </div>
        <!-- 商品 -->
        <div class="goods-list">
          <div class="goods" v-for="item in $store.state.shopCarList" :key="item.id">
            <van-checkbox checked-color="#ee0a24" v-model="item.isSelected" @change="changeSelected($event, item.id)" />
            <div class="box">
              <img :src="getGoods(item.id).thumb_path" />
              <div class="text">
                <div class="title">{{ getGoods(item.id).title }}</div>
                <div class="particulars">
                  <div class="price">￥{{ getGoods(item.id).sell_price }}</div>
                  <van-stepper v-model="item.number" @change="changeNumber($event, item.id)" />
                  <van-button type="danger" @click="del(item.id)">删除</van-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <van-submit-bar tip="默认只支持微信支付" :price="totalPrice * 100" button-text="去结算付款" @submit="onSubmit">
        <template #default>共{{ totalNum }}件商品</template>
      </van-submit-bar>
    </template>

    <div class="empty" v-else>
      <img src="../assets/images/car.png" alt="" />
      <div class="text1">购物车竟然是空的</div>
      <div class="text2">再忙，也要买点什么犒劳自己~</div>
      <van-button @click="$router.push('/home')">去首页逛逛</van-button>
    </div>
    <div class="login" v-if="!$store.state.token">
      <van-button type="danger" @click="$router.push('/login')">立即登录</van-button>
    </div>
  </div>
</template>

<script>
import { getShopCarList, commitOrder } from "@/api/";
export default {
  data() {
    return {
      shopCarListId: [],
      goodsList: [],
      totalNum: 0,
      totalPrice: 0,
      addressId: 0,
      newAddress: this.$store.state.address,
    };
  },
  methods: {
    // 提交订单
    async onSubmit() {
      // 判断是否有选中的商品
      if (!this.totalNum) {
        this.$toast("请选择商品");
        return;
      }
      // 判断是否选中地址
      if (!this.newAddress.id) {
        this.$toast("请选择地址");
        return;
      }
      // 订单编号
      let randomNum = "";
      for (let i = 0; i < 5; i++) {
        randomNum += parseInt(Math.random() * 10);
      }
      let orderSerialNum = this.$moment(Date.now()).format("YYYYMMDDHHmmss") + randomNum;

      let selectedId = [];
      this.$store.state.shopCarList.forEach((item) => {
        if (item.isSelected) {
          selectedId.push(item.id);
        }
      });

      let orderInfo = {
        order_id: orderSerialNum,
        address_id: this.newAddress.id,
        total_price: this.totalPrice,
        number: this.totalNum,
        goods_ids: selectedId.join(","),
      };
      console.log(orderInfo);
      let { code } = await commitOrder(orderInfo);
      if (code === 20000) {
        this.$router.push("/orderdetail/" + orderSerialNum);
      }
      let shopCarList = [];
      this.$store.state.shopCarList.forEach((item) => {
        if (!item.isSelected) {
          shopCarList.push(item);
        }
      });
      this.$store.commit("setShopCarList", shopCarList);
    },
    // 更改地址
    onAdd() {
      this.$router.push("/address");
    },
    getGoods(id) {
      return this.goodsList.filter((item) => item.id === id)[0];
    },
    // 更改是否选中
    changeSelected(bool, id) {
      let shopCarList = this.$store.state.shopCarList.map((item) => {
        if (item.id === id) {
          item.isSelected = bool;
        }
        return item;
      });
      this.$store.commit("setShopCarList", shopCarList);
    },
    // 改变数量
    changeNumber(value, id) {
      let shopCarList = this.$store.state.shopCarList.map((item) => {
        if (item.id === id) {
          item.number = value;
        }
        return item;
      });
      this.$store.commit("setShopCarList", shopCarList);
    },
    // 删除商品
    async del(id) {
      this.shopCarListId = this.shopCarListId.filter((item) => {
        return item !== id;
      });
      let { message } = await getShopCarList(this.shopCarListId.join(","));
      this.goodsList = message;
      let shopCarList = this.$store.state.shopCarList.filter((item) => {
        return item.id !== id;
      });
      this.$store.commit("setShopCarList", shopCarList);
    },
  },
  async mounted() {
    // 获取购物车商品列表
    this.$store.state.shopCarList.forEach((item) => {
      this.shopCarListId.push(item.id);
    });
    let { message } = await getShopCarList(this.shopCarListId.join(","));
    this.goodsList = message;

    // 选中的数量
    this.$store.state.shopCarList.forEach((item) => {
      if (item.isSelected) {
        this.totalNum += item.number;
      }
    });
    // 总价格
    this.$store.state.shopCarList.forEach((item) => {
      if (item.isSelected) {
        this.totalPrice += parseInt(item.number) * parseInt(item.price);
      }
    });
  },
  computed: {
    shopCarList() {
      return this.$store.state.shopCarList;
    },
  },
  watch: {
    shopCarList: {
      handler(newV) {
        this.totalPrice = 0;
        this.totalNum = 0;
        // 总数量
        newV.forEach((item) => {
          if (item.isSelected) {
            this.totalNum += item.number;
          }
        });
        // 总价格
        newV.forEach((item) => {
          if (item.isSelected) {
            this.totalPrice += parseInt(item.number) * parseInt(item.price);
          }
        });
      },
      deep: true,
    },
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "particulars") {
      to.meta.isShowBackIcon = true;
    } else {
      to.meta.isShowBackIcon = false;
    }
    next();
  },
};
</script>

<style lang="scss" scoped>
.shopcar-contain {
  .empty {
    text-align: center;

    img {
      width: 110px;
      height: 110px;
      margin: 30px auto;
    }

    .text1 {
      margin-bottom: 15px;
      font-size: 18px;
      text-align: center;
    }

    .text2 {
      margin-bottom: 30px;
      font-size: 13px;
      text-align: center;
    }

    .van-button {
      background: transparent;
      border: 1px solid #ccc;
    }
  }

  .login {
    margin-top: 30px;
    text-align: center;

    .van-button {
      border-radius: 20px;
    }
  }

  .van-contact-card {
    margin-top: 5px;
  }

  .address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 5px 10px;
    margin-top: 5px;
    background: #fff;
    border-radius: 6px;

    .van-icon {
      color: #969799;
    }

    .left {
      display: flex;
      align-items: center;

      .van-icon {
        margin-right: 10px;
        color: red;
      }

      .text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        font-size: 14px;
        line-height: 20px;

        .particulars {
          font-size: 16px;
          font-weight: 700;
        }
      }
    }
  }

  ::v-deep .line {
    // position: absolute;
    // right: 0;
    // bottom: 0;
    display: flex;
    justify-content: space-evenly;
    width: 100%;
    padding: 2px;
    background: #fff;

    .item {
      width: 14px;
      height: 5px;
      margin: 0;
      transform: skewX(-45deg);
    }

    .bg11 {
      background-color: rgb(12 171 234);
    }

    .bg01 {
      background-color: rgb(226 13 13);
    }
  }

  .goods-list {
    .goods {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 5px;
      margin: 5px 2px;
      background: #fff;
      border-radius: 6px;

      .box {
        display: flex;
        justify-content: space-between;
        padding: 10px;

        img {
          width: 82px;
          height: 100px;
        }

        .text {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          width: 236px;
          padding: 15px;

          .title {
            overflow: hidden;
            font-size: 16px;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .particulars {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .price {
              font-size: 16px;
              color: red;
            }

            .van-button {
              width: 55px;
              height: 32px;
              padding: 0 6px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }

  .van-submit-bar {
    margin-bottom: 50px;
  }
}
</style>
